//
//  NoteDetailViewController.m
//  OrangeNote
//
//  Created by lanou3g on 16/1/22.
//  Copyright © 2016年 崇龙. All rights reserved.
//

#import "NoteDetailViewController.h"
#import "NoteModel.h"
#import "LocalDataManager.h"
#import "RKRichTextView.h"
#import "NotebookModel.h"
#import "NoteListTableViewController.h"
#define kMainScreen [UIScreen mainScreen].bounds




@interface NoteDetailViewController ()<RKRichTextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,strong)RKRichTextView *richTextView;
@property(nonatomic,strong)UITextView *titleView;
//用来接收传来属性的值对象
@property(nonatomic,strong)NoteModel *noteModel;
@property(nonatomic,strong)NSString *bookid;



@end

@implementation NoteDetailViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    RKRichTextView *richTextView = [[[RKRichTextView alloc] initWithFrame:CGRectMake(20, 40, self.view.frame.size.width-40, 200)] autorelease];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    
    
    _titleView = [[UITextView alloc] initWithFrame:CGRectMake(100, 0, kMainScreen.size.width-100, 45)];
    _titleView.layer.borderWidth = 0.3;
    _titleView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    
    _titleView.backgroundColor = [UIColor whiteColor];
    _titleView.textAlignment = NSTextAlignmentLeft;
    _titleView.scrollEnabled = NO;
    _titleView.font = [UIFont systemFontOfSize:23];
    [self.view addSubview:_titleView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 45)];
    titleLabel.backgroundColor = [UIColor whiteColor];
    titleLabel.text = @"标题:";
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLabel];
    
    _richTextView  = [[[RKRichTextView alloc] initWithFrame:CGRectMake(0, 45, kMainScreen.size.width,kMainScreen.size.height-49-45)] autorelease];
    _richTextView.backgroundColor = [UIColor whiteColor];
    _richTextView.scrollView.alwaysBounceHorizontal = NO;
    _richTextView.scrollView.scrollEnabled = YES;
    _richTextView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 20, 0);
    
    [self.view addSubview:_richTextView];
   
   
    self.navigationItem.titleView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Icon-Small"]];

    //上个页面穿过来的值
    _bookid = _bookID;
    _noteModel = _note;
    NSLog(@"%@",_noteModel);
    //判断是点击 cell 进来的还是点击添加按钮进来的
    if (_noteModel) {
         _richTextView.text = _noteModel.content;
        _richTextView.aDelegate = self;
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style: UIBarButtonItemStyleDone target:self action:@selector(updataToDB)];
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.hidden = NO;
        _titleView.text = _note.name;
        
    }else{
        _richTextView.text = @"";
        _richTextView.aDelegate = self;
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveToDataBase)];
        self.navigationController.navigationBar.translucent = NO;

    }
   
}

#pragma mark =====相机调用=======
-(void)isCameraEnable{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];

    //调用相机
    UIAlertAction *camera  =[UIAlertAction actionWithTitle:@"相机" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (sourceType) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate  = self;
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            [self presentViewController:picker animated:YES completion:nil];
            
        }else{
            UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"提示" message:@"相机不可用" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alt show];
        }
        
    }];
    
    //调用图库
    UIAlertAction *albumn = [UIAlertAction actionWithTitle:@"图库" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        //判断是否是可用的类型
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = YES;
        [self presentViewController:pickerImage animated:YES completion:nil];
    }];
    
    //取消按钮
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
        
    }];
    
    [alert addAction:camera];
    [alert addAction:albumn];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:^{
        NSLog(@"alertViewCOntroller show");
    } ];
    
    
}

#pragma mark ========UIPickerViewControllerDelegate方法=======
//3.x 点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    //设置图片尺寸
    CGSize imagesize = image.size;
    if (imagesize.height > imagesize.width) {
        imagesize.height = 350;
        imagesize.width = 250;
       image = [self imageWithImage:image scaledToSize:imagesize];
        
    }else{
        imagesize.height = 200;
        imagesize.width = kMainScreen.size.width-20 ;
         image = [self imageWithImage:image scaledToSize:imagesize];
    }
    if (image == nil) {
        image = info[UIImagePickerControllerOriginalImage];
    }
    
    _richTextView.text = [_richTextView.text stringByAppendingString:[self htmlForJPGImage:image]];
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //将拍的照片保存在本地相册
    //    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    //    // Request to save the image to camera roll
    //    [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
    //        if (error) {
    //            NSLog(@"error");
    //        } else {
    //            NSLog(@"url %@", assetURL);
    //           _urlOfImg =  [NSString stringWithContentsOfURL:assetURL encoding:NSUTF8StringEncoding error:nil];
    //             NSString *imgPath  = [NSString stringWithFormat:@"<img src=\"%@\" width=\"300\" height=\"200\"><br>",_urlOfImg];
    //            _richTextView.text = [_richTextView.text stringByAppendingString:assetURL];
    //            NSLog(@"urlString 是多少呢%@",_urlOfImg);
    //        }
    //    }];
    
    
    
    //     [self imageUpload:image];
}

//编码图片
- (NSString *)htmlForJPGImage:(UIImage *)image
{
    NSData *imageData = UIImageJPEGRepresentation(image,1);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
    return [NSString stringWithFormat:@"<br><a href='pic:%@'><img class='shadow' src='%@' width='%f' height='%f' align='center'></a><br>",imageSource,imageSource,image.size.width,image.size.height];
   
}



//对图片尺寸进行压缩
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//2.x  用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary *)editingInfo
{
    NSLog(@"2.x");
    NSMutableDictionary * dict= [NSMutableDictionary dictionaryWithDictionary:editingInfo];
    
    [dict setObject:image forKey:@"UIImagePickerControllerEditedImage"];
    
    //直接调用3.x的处理函数
    [self imagePickerController:picker didFinishPickingMediaWithInfo:dict];
    
    
    
}
//点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil ];
}
//上传图片方法
- (void) imageUpload:(UIImage *) image{
    //把图片转换成imageDate格式
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    //传送路径
    NSString *urlString = @"http://＊＊＊＊＊/test/upload.php";
    //建立请求对象
    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
    //设置请求路径
    [request setURL:[NSURL URLWithString:urlString]];
    //请求方式
    [request setHTTPMethod:@"POST"];

}


#pragma  mark========保存到本地数据库====================
-(void)saveToDataBase{
    NSLog(@"保存到本地,及云端");
    
    //保存在本地数据库方法
    LocalDataManager *manager = [LocalDataManager sharedDataBase];
    
    
    //插入新的 model
    NoteModel *model = [[NoteModel alloc] init];
    
    model.notebookID = _bookID;
    NSLog(@"_bookID-------------%@",_bookID);
    model.name = _titleView.text;
    model.content = _richTextView.text;
    NSLog(@"model.content==============================%@",model.content);
    
    [manager insertNoteWithModel:model];
    
    self.saveNoteUpdate();
    [self.navigationController popViewControllerAnimated:YES];
    
   

    
}


-(void)updataToDB{

    
    //保存在本地数据库方法
    LocalDataManager *manager = [LocalDataManager sharedDataBase];

    //更新数据库
    _noteModel.content = _richTextView.text;
    _noteModel.name = _titleView.text;
    [manager updateNoteWithNoteID:_noteModel.ID andNote:_noteModel];

    
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    self.noteListUpdate();
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
